﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace cmsservice.Common
{
    public class TradeDateHandler
    {
        private static List<DateTime> lst = new List<DateTime>();

        /// <summary>
        /// 获取指定日期后的交易日
        /// </summary>
        /// <param name="dtStart"></param>
        /// <param name="tradeDays"></param>
        /// <returns></returns>
        public static DateTime GetNextTradeDate(DateTime dtStart, int tradeDays)
        {
            DateTime dtTradeDate = dtStart;
            if (tradeDays > 0)
            {
                while (tradeDays > 0)
                {
                    dtTradeDate = dtTradeDate.AddDays(1);

                    if (IsTradeDate(dtTradeDate))
                    {
                        tradeDays--;
                    }
                }

                return dtTradeDate;
            }
            else
            {
                return DateTime.MinValue;
            }
        }

        /// <summary>
        /// 判断是否为交易日
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static bool IsTradeDate(DateTime date)
        {
            if (lst.Count == 0)
            {
                var path = string.Concat(AppDomain.CurrentDomain.BaseDirectory, "/App_Data/fjyr.xml");

                XmlDocument xml = new XmlDocument();
                xml.Load(path);
                var root = xml.DocumentElement;
                var nodes = root.SelectNodes("date");
                foreach (XmlNode node in nodes)
                {
                    DateTime oDate = DateTime.MinValue;
                    if (DateTime.TryParse(node.InnerText, out oDate))
                    {
                        lst.Add(oDate);
                    }
                }
            }

            date = date.Date;
            if (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday)
            {
                return false;
            }
            else
            {
                return !lst.Any(x => x == date);
            }
        }
    }
}
